package com.youkang.youkangseleniumjava.controller;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.youkang.youkangseleniumjava.utils.CloseableHttpClientUtil;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 邓昕劼
 * @version 1.3
 */

@Component

public class SeleniumController {
    //selenium驱动
    private WebDriver driver;
    public static final Logger logger = LoggerFactory.getLogger(SeleniumController.class);
    //生产环境
     String test = "http://47.101.35.17:8082";
    //测试环境
//    String test = "http://localhost:8082";
    String LoginUrl = test + "/api/user/loginWx";
    String token = null;
    String sessionId = null;

    //优康老人护理员工单导入
//   @Scheduled(cron = "* * * * * *")
    @Scheduled(cron = "0 0 18 * * ?")
    public void Selenium() {
        try {
            logger.info("开始配置Selenium");
            /**
             * 开始SeleniumD:\drever1
             */
            System.setProperty("webdriver.gecko.driver", "C:/driver/geckodriver.exe");
            // System.setProperty("webdriver.gecko.driver", "D:/drever1/geckodriver.exe");
            System.setProperty("webdriver.firefox.bin", "C:/火狐浏览器/firefox.exe");
            // 创建 FirefoxOptions 对象
            FirefoxOptions options = new FirefoxOptions();
            // 设置无头模式
             options.setHeadless(true);
            // 创建 FirefoxDriver 对象，使用设置好的 FirefoxOptions
            driver = new FirefoxDriver(options);
            WebDriverWait wait = new WebDriverWait(driver, 100);
            // 创建WebDriverWait对象
            driver.get("https://hlf.yly99.com/login");
            driver.manage().window().maximize();
            logger.info("开始爬取、老人客户列表");
            // driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);// 隐式等待时长为20秒
            /*
             * 登录   输入1、账号 2、密码 3、点击同意协议 4、点击登录
             */
            WebElement xpathLoginUserInput = driver.findElement(By.xpath("/html/body/div/div/div/div[1]/div/form/div[1]/div/div/input"));
            xpathLoginUserInput.sendKeys("13359009852");
            WebElement xpathLoginPasswordInput = driver.findElement(By.xpath("/html/body/div/div/div/div[1]/div/form/div[2]/div/div/input"));
            xpathLoginPasswordInput.sendKeys("Yk123456@");
            WebElement xpathLoginRuleInput = driver.findElement(By.xpath("/html/body/div/div/div/div[1]/div/form/div[3]/div/div/div[1]/label/span[1]/span"));
            xpathLoginRuleInput.click();
            WebElement xpathLoginInput = driver.findElement(By.xpath("/html/body/div/div/div/div[1]/div/form/button"));
            xpathLoginInput.click();
            /*
             * 登录成功进入养老云99的页面   开始获取客户管理的数据（老人数据）
             */
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div/div/div[1]/div[1]/div/ul/div[2]/div[2]/a/li")));
            WebElement xpathOldManInput = driver.findElement(By.xpath("/html/body/div/div/div[1]/div[1]/div/ul/div[2]/div[2]/a/li"));
            xpathOldManInput.click();
            waitPageLoadComplete(driver, 30);
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody")));
            //找到客户管理总共有多少数据的li
            WebElement xpathOldManSumLi = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[3]/div/div/div[1]"));
            String xpathOldManSumText = xpathOldManSumLi.getText();
            //对上面的字符串进行截取截出里面总共有多少条数据的字符
            // 使用正则表达式匹配数字
            Pattern pattern = Pattern.compile("\\d+");
            Matcher matcher = pattern.matcher(xpathOldManSumText);
            int xpathOldManSumInt = 0;
            if (matcher.find()) {
                xpathOldManSumInt = Integer.parseInt(matcher.group());
            }
            //总页数
            int xpathOldManSumIntTotalPage = xpathOldManSumInt % 10 == 0 ? xpathOldManSumInt / 10 : xpathOldManSumInt / 10 + 1;
//            int xpathOldManSumIntTotalPage = 100;
            //计数
            int xpathOldManSumIntCount = 1;
            logger.info("客户列表总共数据："+xpathOldManSumInt);
            logger.info("客户列表页数："+xpathOldManSumIntTotalPage);
            //获取单日工单表格的数据
            waitPageLoadComplete(driver, 30);
            //最终传入api的 客户管理得数据
            JSONObject oldMan = new JSONObject();
            //将数据全部的老人数据存到这个里面，最后会添加到oldMan里面去
            JSONArray customer = new JSONArray();
            while (xpathOldManSumIntCount <= xpathOldManSumIntTotalPage) {
                //手动调用GC回收对象
                System.gc();
                //刷新页面清楚缓存，解决内存泄漏的情况
                driver.navigate().refresh();
                Thread.sleep(1000);
                wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[3]/div/div/div[2]/input")));
                //前往第几页  为了能够刷新页面清楚缓存
                String xpathOldManSumIntCountString = String.valueOf(xpathOldManSumIntCount);
                WebElement xpathOldManNextPage1 = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[3]/div/div/div[2]/input"));
                xpathOldManNextPage1.sendKeys(xpathOldManSumIntCountString);
                Thread.sleep(3000);
                WebElement xpathOldManNextPage2 = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[3]/div/div/div[2]/input"));
                //填完之后点击TAB前往
                xpathOldManNextPage2.sendKeys(Keys.TAB);
                Thread.sleep(4000);
                //里面是ul形式的先获取第一页的ul
                wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[4]/div[2]/table/tbody")));
                WebElement ul = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[4]/div[2]/table/tbody"));
                List<WebElement> trS = ul.findElements(By.tagName("tr"));
                int i = 1;
                boolean compile = false;
                for (WebElement webElement : trS) {
                    //将每一条的数据存到 hashmap里面
                    JSONObject map = new JSONObject();
                    //每点击一个老人详情，创建一个类，保存老人信息
                    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody/tr[1]/td[8]/div")));

                    /**
                     *  *************************只获取当天操作的操作的客户信息***************************
                     */
                    WebElement operationTime = webElement.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody/tr[" + i + "]/td[9]/div"));
                    String operationTimeText = operationTime.getText();
                    if (operationTimeText != null || Objects.equals(operationTimeText, "")) {
                        operationTimeText = operationTimeText.substring(0, 10);
                        java.util.Date day2 = new java.util.Date();
                        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
                        String format2 = sdf2.format(day2);
                        if (!format2.equals(operationTimeText)) {
                            xpathOldManSumIntTotalPage = 0;
                            break;
                        }
                    }
                    /**
                     * **************************只获取当天操作的操作的客户信息***************************
                     */

                    // 使用 findElements 查找所有匹配的元素
                    WebElement status = webElement.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody/tr[" + i + "]/td[8]/div"));
                    String statu = status.getText();
                    //状态为正常和暂停的时候就点击编辑按钮
                    if (status.getText().equals("正常") || status.getText().equals("暂停")) {
                        //点击编辑按钮，打开更加详细得页面
                        WebElement editButton = webElement.findElement(By.xpath("/html/body/div/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[5]/div[2]/table/tbody/tr[" + i + "]/td[10]/div/button[1]"));
                        // 使用 JavaScript 执行点击操作
                        ((JavascriptExecutor) driver).executeScript("arguments[0].click();", editButton);
                        // editButton.click();
                        i++;
                        compile = true;
                    }
                    if (status.getText().equals("已转入新站") || status.getText().equals("终止")) {
                        //状态为已转入其他站 就直接获取页面是仅有的数据，因为他没有编辑按钮
                        i++;
                        compile = false;
                    }
                    //如果是暂停和正常的数据才有 编辑页面 获取编辑页面里面的数据
                    if (compile) {
                        Thread.sleep(1000);
                        /**
                         * 这里是进到了每一个老人的编辑页面所以在这里取获取数据
                         */
                        //最终的数据
                        String[] arr0 = new String[30];
                        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div/div/div[2]/div/section/div/div[1]/form")));
                        WebElement form = driver.findElement(By.xpath("/html/body/div/div/div[2]/div/section/div/div[1]/form"));
                        List<WebElement> inputs = form.findElements(By.xpath(".//input"));
                        int counts = 0;
                        // Thread.sleep(1000);
                        for (WebElement input : inputs) {
                            String value = input.getAttribute("value");
                            arr0[counts] = value;
                            counts++;
                        }
                        map.put("status", statu);
                        //遍历最终数据存到对象中
                        int countArr0 = 0;
                        for (String s : arr0) {
                            if (countArr0 == 0) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("ApplicationNumber", s);
                                }else{
                                    map.put("ApplicationNumber", null);
                                }
                            }//申请号
                            if (countArr0 == 1) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("EvaluationPeriod", s);
                                }else{
                                    map.put("EvaluationPeriod", null);
                                }
                            }//评估有效期
                            if (countArr0 == 2) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("EvaluationLervl", extractChineseNumber(s));
                                }else{
                                    map.put("EvaluationLervl", null);
                                }
                            }//评估等级
                            if (countArr0 == 3) {
                                logger.info(s +" "+ statu);
                                if (s!=null&&!s.isEmpty()){
                                    map.put("Name", s);
                                }else{
                                    map.put("Name", null);
                                }
                            }//姓名
                            if (countArr0 == 4) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("IdentityCard", s);
                                }else{
                                    map.put("IdentityCard", null);
                                }
                            }//身份证
                            if (countArr0 == 5) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("dateOfBirth", s);
                                }else{
                                    map.put("dateOfBirth", null);
                                }
                            }//出生年月
                            if (countArr0 == 8) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("Age", s);
                                }else{
                                    map.put("Age", null);
                                }
                            }//年龄
                            if (countArr0 == 9) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("MedicareCard", s);
                                }else{
                                    map.put("MedicareCard", null);
                                }
                            }//医保卡号
                            if (countArr0 == 15) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("AddressDetall", s);
                                }else{
                                    map.put("AddressDetall", null);
                                }
                            }//详细地址
                            if (countArr0 == 16) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("AddressDetall", map.get("AddressDetall") + s);
                                }else{
                                    map.put("AddressDetall", null);
                                }
                            }//详细地址
                            if (countArr0 == 17) {
                                if (s == null || s.equals("")) {
                                    map.put("Latltude", null);
                                    map.put("Longltude", null);
                                } else {
                                    String[] parts = s.split(",");
                                    map.put("Latltude", parts[1]);
                                    map.put("Longltude", parts[0]);
                                }
                            }//经度 //维度
                            if (countArr0 == 20) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("Moblle", s);
                                }else{
                                    map.put("Moblle", null);
                                }
                            }//电话号码
                            if (countArr0 == 21) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("Sreet", s);
                                }else{
                                    map.put("Sreet", null);
                                }
                            }//街道
                            if (countArr0 == 12) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("gerontocracy", s);
                                }else{
                                    map.put("gerontocracy", null);
                                }
                            }//老人性质
                            if (countArr0 == 18) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("PersonalNature", s);
                                }else{
                                    map.put("PersonalNature", null);
                                }
                            }//个人性质
                            countArr0++;
                        }
                        map.put("MedicareCardType", "医保卡");
                        //将数据添加进去
                        customer.add(map);
                    } else {
                        //这个里面的话是终止的客户数据，因为他没有编辑页面所以数据少一点
                        WebElement applicationNumber = webElement.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody/tr[" + (i - 1) + "]/td[2]/div"));
                        WebElement name = webElement.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody/tr[" + (i - 1) + "]/td[3]/div"));
                        WebElement identityCard = webElement.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody/tr[" + (i - 1) + "]/td[4]/div"));
                        WebElement street = webElement.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody/tr[" + (i - 1) + "]/td[5]/div"));
                        WebElement assessmentGrade = webElement.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody/tr[" + (i - 1) + "]/td[6]/div"));
                        WebElement assessmentDate = webElement.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody/tr[" + (i - 1) + "]/td[7]/div"));
                        if (statu!=null&&!statu.isEmpty()){
                            map.put("status", statu);
                        }else{
                            map.put("status", null);
                        }
                        if (applicationNumber.getText()!=null&&!applicationNumber.getText().isEmpty()){
                            map.put("ApplicationNumber", applicationNumber.getText());//申请号
                        }else{
                            map.put("ApplicationNumber", null);
                        }
                        if (name.getText()!=null&&!name.getText().isEmpty()){
                            map.put("Name", name.getText());//姓名
                        }else{
                            map.put("Name", null);
                        }
                        if (identityCard.getText()!=null&&!identityCard.getText().isEmpty()){
                            map.put("IdentityCard", identityCard.getText());//身份证
                        }else{
                            map.put("IdentityCard", null);
                        }
                        if (street.getText()!=null&&!street.getText().isEmpty()){
                            map.put("Sreet", street.getText());
                        }else{
                            map.put("Sreet", null);
                        }
                        if (assessmentGrade.getText()!=null&&!assessmentGrade.getText().isEmpty()){
                            map.put("EvaluationLervl", extractChineseNumber(assessmentGrade.getText()));//评估等级
                        }else{
                            map.put("EvaluationLervl", null);
                        }
                        if (assessmentDate.getText()!=null&&!assessmentDate.getText().isEmpty()){
                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                            java.util.Date utilDate = dateFormat.parse(assessmentDate.getText());
                            java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
                            map.put("EvaluationPeriod", sqlDate.toString().substring(0,10));//评估有效期
                        }else{
                            map.put("EvaluationPeriod", null);
                        }
                        if (statu.equals("已转入新站")) {
                            logger.info(name.getText() + "已转入新站");
                        }
                        if (statu.equals("终止")) {
                            logger.info(name.getText() + "终止");
                        }
                        map.put("MedicareCardType", "医保卡");
                        //将数据添加进去
                        customer.add(map);
                    }
                    /**
                     *   将每一条数据都写入进去
                     */
                    Calendar calendar = Calendar.getInstance();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    oldMan.put("time", dateFormat.format(calendar.getTime()));
                    oldMan.put("customer", customer);

//                    // 下面   测试数据 将数据写到桌面上面的记事本里面去了   所加
//                    String pretty = JSON.toJSONString(oldMan, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
//                            SerializerFeature.WriteDateUseDateFormat);
//                    String path = "C:\\Users\\邓昕劼\\Desktop";
//                    //判断文件是否存在
//                    File file = new File(path + "/老人.txt");
//                    if (file.exists()) {
//
//                    } else {
//                        try {
//                            file.createNewFile();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//
//                    try {
//                        FileOutputStream fileOutputStream = new FileOutputStream(file);
//                        fileOutputStream.write(pretty.getBytes());
//                        fileOutputStream.close();
//                        System.out.println("老人json数据保存到成功！！！");
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
                    // 上面  测试数据所加
//                    System.out.println("oldMan = " + oldMan);


                    //返回客户管理
                    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div/div/div[1]/div[1]/div/ul/div[2]/div[2]/a/li")));
                    WebElement xpathOldManInput2 = driver.findElement(By.xpath("/html/body/div/div/div[1]/div[1]/div/ul/div[2]/div[2]/a/li"));
                    ((JavascriptExecutor) driver).executeScript("arguments[0].click();", xpathOldManInput2);
//                        xpathOldManInput2.click();

                }
                xpathOldManSumIntCount++;
//                Thread.sleep(3000);
//                System.out.println("xpathOldManSumIntCount = " + xpathOldManSumIntCount);
                logger.info("老人页数："+xpathOldManSumIntCount);
            }
            if (oldMan.size()!=0) {
                /**
                 * 访问长护宝 老人导入接口  最后
                 */
                logger.info(" 老人导入Api 登录长护宝获取token！");
                String[] customerStrList = token();
                token = customerStrList[0];
                sessionId = customerStrList[1];
                logger.info("token = " + token);
                logger.info("sessionId = " + sessionId);
                logger.info("开始访问长护宝 老人导入API");
                String customerImport = test + "/api/wandaImport/customerImport";
                Map<String, String> customerHeaMap = new HashMap<>();
                customerHeaMap.put("Content-Type", "application/json");
                customerHeaMap.put("token", token);
                customerHeaMap.put("Cookie", "JSESSIONID=" + sessionId);
                String customerResult = CloseableHttpClientUtil.doPostRaw(customerImport, oldMan.toString(), customerHeaMap);
                logger.info("访问长护宝 老人导入API结果：" + customerResult);
            }

            /**
             * 到这里的话应该是 客户管理的数据全部爬完了
             */
            //现在去点击人员管理去爬人员管理的信息
            //点击机构管理
            logger.info("开始爬取人员护理员管理");
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[1]/div[1]/div/ul/div[2]/div[4]/li")));
            WebElement organizationButton = driver.findElement(By.xpath("/html/body/div[1]/div/div[1]/div[1]/div/ul/div[2]/div[4]/li"));
            organizationButton.click();
            //点击人员管理
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[1]/div[1]/div/ul/div[2]/div[4]/li/ul/div[2]/a")));
            WebElement staffButton = driver.findElement(By.xpath("/html/body/div[1]/div/div[1]/div[1]/div/ul/div[2]/div[4]/li/ul/div[2]/a"));
            staffButton.click();
            //等待人员管理里面的元素可见
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody")));
            //找到人员管理总共有多少数据的li
            WebElement organizationSumLi = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[3]/div/div/div[1]"));
            String organizationSumText = organizationSumLi.getText();
            //对上面的字符串进行截取截出里面总共有多少条数据的字符
            // 使用正则表达式匹配数字
            Pattern patternOrganization = Pattern.compile("\\d+");
            Matcher matcherOrganization = patternOrganization.matcher(organizationSumText);
            int OrganizationSumInt = 0;
            if (matcherOrganization.find()) {
                OrganizationSumInt = Integer.parseInt(matcherOrganization.group());
            }
            //总页数
            int OrganizationSumIntTotalPage = OrganizationSumInt % 10 == 0 ? OrganizationSumInt / 10 : OrganizationSumInt / 10 + 1;
//            int OrganizationSumIntTotalPage = 1;
            //计数
            int OrganizationSumIntCount = 1;
            logger.info("员工护理员列表总共数据："+OrganizationSumInt);
            logger.info("员工护理员列表页数："+OrganizationSumIntTotalPage);
            //最终传入api的 员工管理得数据
            JSONObject staff = new JSONObject();
            //将数据全部的护理员数据存到这个里面，最后会添加到staff里面去
            JSONArray caregiver = new JSONArray();

            while (OrganizationSumIntCount <= OrganizationSumIntTotalPage) {
                //手动调用GC回收对象
                System.gc();
                //刷新页面清楚缓存，解决内存泄漏的情况
                driver.navigate().refresh();
                wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[3]/div/div/div[2]/input")));
                //前往第几页  为了能够刷新页面清楚缓存
                String xpathOldManSumIntCountString = String.valueOf(OrganizationSumIntCount);
                WebElement xpathOldManNextPage1 = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[3]/div/div/div[2]/input"));
                xpathOldManNextPage1.sendKeys(xpathOldManSumIntCountString);
                Thread.sleep(3000);
                WebElement xpathOldManNextPage2 = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[3]/div/div/div[2]/input"));
                //填完之后点击TAB前往
                xpathOldManNextPage2.sendKeys(Keys.TAB);
                Thread.sleep(3000);
                //里面是ul形式的先获取第一页的ul
                wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody")));
                WebElement ul2 = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody"));
                List<WebElement> tr2S = ul2.findElements(By.tagName("tr"));
                int i2 = 1;
                for (WebElement webElement : tr2S) {
                    //将每一条的数据存到 hashmap里面
                    JSONObject map = new JSONObject();
                    //每点击一个老人详情，创建一个类，保存老人信息
                    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody/tr[1]/td[9]/div")));


                    /**
                     *  *************************只获取当天操作的操作的员工信息***************************
                     */
                    WebElement operationTime = webElement.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody/tr[" + i2 + "]/td[11]/div"));
                    String operationTimeText = operationTime.getText();
                    if (operationTimeText != null || Objects.equals(operationTimeText, "")) {
                        operationTimeText = operationTimeText.substring(0, 10);
                        java.util.Date day2 = new java.util.Date();
                        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
                        String format2 = sdf2.format(day2);
                        if (!format2.equals(operationTimeText)) {
                            OrganizationSumIntTotalPage = 0;
                            break;
                        }
                    }
                    /**
                     * **************************只获取当天操作的操作的员工信息***************************
                     */


                    // 使用 findElements 查找所有匹配的元素
                    WebElement status2 = webElement.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody/tr[" + i2 + "]/td[9]/div"));
                    //状态为正常和暂停的时候就点击编辑按钮
                    String statu2 = status2.getText();
                    if (statu2.equals("在职")) {
                        map.put("status", statu2);
                        //在职
                        //点击编辑按钮，打开更加详细得页面
                        WebElement editButton1 = webElement.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[5]/div[2]/table/tbody/tr[" + i2 + "]/td[12]/div/button[1]"));
                        // 使用 JavaScript 执行点击操作
//                        ((JavascriptExecutor) driver).executeScript("arguments[0].click();", editButton1);
                        editButton1.click();
                        /**
                         * 这里是进到了每一个护理员的编辑页面所以在这里取获取数据
                         */
                        //最终的数据
                        String[] arr02 = new String[30];
                        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div/div/div[2]/div/section/div/div/form")));
                        WebElement form2 = driver.findElement(By.xpath("/html/body/div/div/div[2]/div/section/div/div/form"));
                        List<WebElement> inputs2 = form2.findElements(By.xpath(".//input"));
                        int counts2 = 0;
                        // Thread.sleep(1000);
                        for (WebElement input : inputs2) {
                            String value = input.getAttribute("value");
                            arr02[counts2] = value;
                            counts2++;
                        }
                        //遍历最终数据存到对象中
                        int countArr02 = 0;
                        for (String s : arr02) {
                            if (countArr02 == 0) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("numbering", s);
                                }else{
                                    map.put("numbering", null);
                                }
                            }//员工编号
                            if (countArr02 == 2) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("nativePlace", s);
                                }else{
                                    map.put("nativePlace", null);
                                }
                            }//籍贯
                            if (countArr02 == 5) {
                                logger.info(s+"="+statu2);
                                if (s!=null&&!s.isEmpty()){
                                    map.put("name", s);
                                }else{
                                    map.put("name", null);
                                }
                            }//姓名
                            if (countArr02 == 6) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("sreet", s);
                                }else{
                                    map.put("sreet", null);
                                }
                            }//街道
                            if (countArr02 == 8) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("moblle", s);
                                }else{
                                    map.put("moblle", null);
                                }
                            }//电话
                            if (countArr02 == 9) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("position", s);
                                }else{
                                    map.put("position", null);
                                }
                            }//职位
                            if (countArr02 == 12) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("identityCard", s);
                                }else{
                                    map.put("identityCard", null);
                                }
                            }//身份证
                            if (countArr02 == 13) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("age", s);
                                }else{
                                    map.put("age", null);
                                }
                            }//年龄
                            if (countArr02 == 19) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("contractStartDate", Date.valueOf(s).toString().substring(0,10));
                                    map.put("contractEndDate", null);
                                    map.put("entryDate", Date.valueOf(s).toString().substring(0,10));
                                }else{
                                    map.put("contractStartDate", null);
                                    map.put("contractEndDate", null);
                                    map.put("entryDate", null);
                                }
                            }//合同开始日期 //合同结束日期 //入职日期
                            if (countArr02 == 22) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("certificateNo", s);
                                }else{
                                    map.put("certificateNo", null);
                                }
                            }//证书编号
                            if (countArr02 == 23) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("levelOfEducation", s);
                                }else{
                                    map.put("levelOfEducation", null);
                                }
                            }//文化程度
                            countArr02++;
                        }
                        map.put("status", "在职");//状态
                        i2++;
                        //将数据添加进去
                        caregiver.add(map);
                    }
                    if (statu2.equals("离职")) {
                        //离职
                        //点击查看档案按钮，打开更加详细得页面
                        WebElement editButton1 = webElement.findElement(By.xpath("/html/body/div/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[5]/div[2]/table/tbody/tr[" + i2 + "]/td[12]/div"));
                        // 使用 JavaScript 执行点击操作
//                        ((JavascriptExecutor) driver).executeScript("arguments[0].click();", editButton1);
                        editButton1.click();
                        String[] arr02 = new String[30];
                        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div/div[2]/div/div[3]/div[1]/div[2]/form")));
                        WebElement form2 = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div/div[2]/div/div[3]/div[1]/div[2]/form"));
                        List<WebElement> inputs2 = form2.findElements(By.xpath(".//span"));
                        int counts2 = 0;
                        // Thread.sleep(1000);
                        for (WebElement input : inputs2) {
                            String value = input.getText();
                            arr02[counts2] = value;
                            counts2++;
                        }
                        //遍历最终数据存到对象中
                        int countArr02 = 0;
                        for (String s : arr02) {
                            if (countArr02 == 1) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("numbering", s);
                                }else{
                                    map.put("numbering", null);
                                }
                            }//员工编号
                            if (countArr02 == 3) {
                                logger.info(s+"="+statu2);
                                if (s!=null&&!s.isEmpty()){
                                    map.put("name", s);
                                }else{
                                    map.put("name", null);
                                }
                            }//姓名
                            if (countArr02 == 4) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("sreet", s);
                                }else{
                                    map.put("sreet", null);
                                }
                            }//街道
                            if (countArr02 == 5) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("moblle", s);
                                }else{
                                    map.put("moblle", null);
                                }
                            }//电话
                            if (countArr02 == 6) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("position", s);
                                }else{
                                    map.put("position", null);
                                }
                            }//职位
                            if (countArr02 == 7) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("identityCard", s);
                                }else{
                                    map.put("identityCard", null);
                                }
                            }//身份证
                            if (countArr02 == 8) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("age", s);
                                }else{
                                    map.put("age", null);
                                }
                            }//合同开始日期
                            if (countArr02 == 14) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("contractStartDate", Date.valueOf(s).toString().substring(0,10));
                                }else{
                                    map.put("contractStartDate", null);
                                }
                            }//合同结束日期
                            if (countArr02 == 15) {
                                if (s!=null&&!s.isEmpty()){
                                    map.put("contractEndDate", Date.valueOf(s).toString().substring(0,10));
                                }else{
                                    map.put("contractEndDate", null);
                                }
                            }//合同结束日期
                            countArr02++;
                        }
                        map.put("status", "离职");//状态
                        i2++;
                        //将数据添加进去
                        caregiver.add(map);
                    }

                    /**
                     *   这里护理员数据已经拿到了下面去访问api
                     */
                    Calendar calendar = Calendar.getInstance();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    staff.put("time", dateFormat.format(calendar.getTime()));
                    staff.put("caregiver", caregiver);


//                    // 下面   测试数据 将数据写到桌面上面的记事本里面去了   所加
//                    String pretty = JSON.toJSONString(staff, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
//                            SerializerFeature.WriteDateUseDateFormat);
//                    String path = "C:\\Users\\邓昕劼\\Desktop";
//                    //判断文件是否存在
//                    File file = new File(path + "/护理员.txt");
//                    if (file.exists()) {
//                    } else {
//                        try {
//                            file.createNewFile();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//
//                    try {
//                        FileOutputStream fileOutputStream = new FileOutputStream(file);
//                        fileOutputStream.write(pretty.getBytes());
//                        fileOutputStream.close();
//                        System.out.println("护理员json数据保存到成功！！！");
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
                    // 上面  测试数据所加
//                    System.out.println("staff = " + staff);

                    //返回客户管理
                    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div/div/div[1]/div[1]/div/ul/div[2]/div[4]/li/ul/div[2]/a/li")));
                    WebElement staffInput2 = driver.findElement(By.xpath("/html/body/div/div/div[1]/div[1]/div/ul/div[2]/div[4]/li/ul/div[2]/a/li"));
                    ((JavascriptExecutor) driver).executeScript("arguments[0].click();", staffInput2);
//                        xpathOldManInput2.click();

                }
                OrganizationSumIntCount++;
                logger.info("护理员页数："+OrganizationSumIntCount);
            }
            if (staff.size()!=0) {
                /**
                 * 访问长护宝 老人导入接口  最后
                 */
                logger.info(" 客户护理员数据导入Api 登录长护宝获取token！");
                String[] CaregiverStrList = token();
                token = CaregiverStrList[0];
                sessionId = CaregiverStrList[1];
                logger.info("token = " + token);
                logger.info("sessionId = " + sessionId);
                logger.info("开始访问长护宝 客户护理员导入API");
                String CaregiverImport = test + "/api/wandaImport/caregiverImport";
                Map<String, String> CaregiverHeaMap = new HashMap<>();
                CaregiverHeaMap.put("Content-Type", "application/json");
                CaregiverHeaMap.put("token", token);
                CaregiverHeaMap.put("Cookie", "JSESSIONID=" + sessionId);
                String caregiverResult = CloseableHttpClientUtil.doPostRaw(CaregiverImport, staff.toString(), CaregiverHeaMap);
                logger.info("访问长护宝  客户护理员导入API结果：" + caregiverResult);
            }


            /**
             * 到这里的话应该是 员工排期的数据全部爬完了   下面开始爬 今天的  工单和服务情况
             */
            //点击工单管理
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[1]/div[1]/div/ul/div[2]/div[5]/li")));
            WebElement workOrderButton = driver.findElement(By.xpath("/html/body/div[1]/div/div[1]/div[1]/div/ul/div[2]/div[5]/li"));
            workOrderButton.click();
            Thread.sleep(1000);
            //点击工单列表
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[1]/div[1]/div/ul/div[2]/div[5]/li/ul/div[1]/a")));
            WebElement workOrderListButton = driver.findElement(By.xpath("//a/li/span[text()='工单列表']"));
            workOrderListButton.click();
            //等待工单列表里面的选择服务时间的控件 因为我们需要选择时间，爬取今天的工单数据和服务情况数据
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[1]/form/div/div[1]/form/div[5]/div/div/div[2]/input")));
            WebElement endTimeButton = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[1]/form/div/div[1]/form/div[5]/div/div/div[2]/input"));
            String endTimeText = endTimeButton.getAttribute("value");
            WebElement wsbeginTimeButton = driver.findElement(By.xpath("/html/body/div/div/div[2]/div/section/div/div[1]/form/div/div[1]/form/div[5]/div/div/div[1]/input"));
            wsbeginTimeButton.clear();
            wsbeginTimeButton.sendKeys(endTimeText);
            wsbeginTimeButton.sendKeys(Keys.ENTER);
            //点击查询按钮查询今天的数据
            Thread.sleep(1000);
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[1]/form/div/div[2]/div/div/button[1]")));
            WebElement wsinquireButton = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[1]/form/div/div[2]/div/div/button[1]"));
//            inquireButton.click();
            ((JavascriptExecutor) driver).executeScript("arguments[0].click();", wsinquireButton);
            Thread.sleep(1000);
            //查到今天的数据 开始爬
            //等待工单列表里面的元素可见
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody")));
            //找到人员管理总共有多少数据的li
            WebElement workOrderSumLi = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div/div[3]/div[1]/div[3]/div/div/div[1]"));
            String workOrderSumText = workOrderSumLi.getText();
            //对上面的字符串进行截取截出里面总共有多少条数据的字符
            // 使用正则表达式匹配数字
            Pattern patternWorkOrder = Pattern.compile("\\d+");
            Matcher matcherWorkOrder = patternWorkOrder.matcher(workOrderSumText);
            int WorkOrderSumInt = 0;
            if (matcherWorkOrder.find()) {
                WorkOrderSumInt = Integer.parseInt(matcherWorkOrder.group());
            }
            //总页数
            int WorkOrderSumIntTotalPage = WorkOrderSumInt % 10 == 0 ? WorkOrderSumInt / 10 : WorkOrderSumInt / 10 + 1;
//            int WorkOrderSumIntTotalPage = 1;
            //计数
            int WorkOrderSumIntCount = 1;
            logger.info("工单列表总共数据："+WorkOrderSumInt);
            logger.info("工单列表页数："+WorkOrderSumIntTotalPage);
            //服务情况数据
            JSONObject serviceSituation = new JSONObject();
            //将数据全部的护理员数据存到这个里面，最后会添加到staff里面去
            JSONArray Situation = new JSONArray();
            //工单数据
            JSONObject workOrderInformation = new JSONObject();
            //将数据全部的护理员数据存到这个里面，最后会添加到staff里面去
            JSONArray workOrder = new JSONArray();
            while (WorkOrderSumIntCount <= WorkOrderSumIntTotalPage) {
                //手动调用GC回收对象
                System.gc();
                //刷新页面清楚缓存，解决内存泄漏的情况
                driver.navigate().refresh();
                Thread.sleep(1000);
                wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[1]/form/div/div[1]/form")));
                WebElement endTimeButton2 = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[1]/form/div/div[1]/form/div[5]/div/div/div[2]/input"));
                String endTimeText2 = endTimeButton2.getAttribute("value");
                WebElement beginTimeButton2 = driver.findElement(By.xpath("/html/body/div/div/div[2]/div/section/div/div[1]/form/div/div[1]/form/div[5]/div/div/div[1]/input"));
                beginTimeButton2.clear();
                beginTimeButton2.sendKeys(endTimeText);
                beginTimeButton2.sendKeys(Keys.ENTER);
                Thread.sleep(1000);
                wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div/div[3]/div[1]/div[3]/div/div/div[2]/input")));
                //前往第几页  为了能够刷新页面清楚缓存
                String WorkOrderSumIntCountString = String.valueOf(WorkOrderSumIntCount);
                WebElement WorkOrderNextPage1 = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div/div[3]/div[1]/div[3]/div/div/div[2]/input"));
                WorkOrderNextPage1.sendKeys(WorkOrderSumIntCountString);
                WebElement WorkOrderNextPage2 = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div/div[3]/div[1]/div[3]/div/div/div[2]/input"));
                //填完之后点击TAB前往
                WorkOrderNextPage2.sendKeys(Keys.TAB);
                Thread.sleep(1000);
                //里面是ul形式的先获取第一页的ul
                wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody")));
                WebElement ul3 = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody"));
                List<WebElement> tr3S = ul3.findElements(By.tagName("tr"));
                int i3 = 1;
                boolean WScompile = false;
                for (WebElement webElement : tr3S) {
                    //工单数据
                    JSONObject workOrderMap = new JSONObject();
                    //服务情况数据
                    JSONObject SituationMap = new JSONObject();
                    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody/tr[1]/td[8]/div")));
                    // 使用 findElements 查找所有匹配的元素
                    WebElement status3 = webElement.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody/tr[" + i3 + "]/td[8]/div"));
                    //状态为正常和暂停的时候就点击编辑按钮
                    String statu3 = status3.getText();
                    if (statu3.equals("服务完成") || statu3.equals("服务中")) {
                        //打开查看页面
                        WebElement wordButton1 = webElement.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div/div[3]/div[1]/div[2]/div[1]/div[5]/div[2]/table/tbody/tr[" + i3 + "]/td[12]/div/button[1]"));
                        // 使用 JavaScript 执行点击操作
                        ((JavascriptExecutor) driver).executeScript("arguments[0].click();", wordButton1);
//                        wordButton1.click();
                        i3++;
                        WScompile = true;
                    }
                    if (statu3.equals("待服务") || statu3.equals("已失效") || statu3.equals("工单作废")) {
                        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div/div[3]/div[1]/div[2]/div[1]/div[5]/div[2]/table/tbody")));
                        //打开查看页面
                        WebElement wordButton1 = null;
                        if (statu3.equals("待服务")) {
                            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div/div[3]/div[1]/div[2]/div[1]/div[5]/div[2]/table/tbody")));
                            wordButton1 = webElement.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div/div[3]/div[1]/div[2]/div[1]/div[5]/div[2]/table/tbody/tr[" + i3 + "]/td[12]/div/button[2]"));
                        }
                        if (statu3.equals("已失效") || statu3.equals("工单作废")) {
                            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div/div[3]/div[1]/div[2]/div[1]/div[5]/div[2]/table/tbody")));
                            wordButton1 = webElement.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div[2]/div/div[3]/div[1]/div[2]/div[1]/div[5]/div[2]/table/tbody/tr[" + i3 + "]/td[12]/div/button"));
                        }
                        // 使用 JavaScript 执行点击操作
                        ((JavascriptExecutor) driver).executeScript("arguments[0].click();", wordButton1);
//                        wordButton1.click();
                        i3++;
                        WScompile = false;
                    }
                    if (WScompile) {
                        Thread.sleep(2000);
                        //最终详情中的数据
                        String[] arr02 = new String[35];
                        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div/div[2]/div/form")));
                        WebElement form = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div/div[2]/div/form"));
                        List<WebElement> labelList = form.findElements(By.xpath(".//span"));
                        //单独获取计划服务时间
                        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div/div[2]/div/form/div[3]/div[2]/div/div[1]/div/div/span")));
                        WebElement serviceTime = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div/div[2]/div/form/div[3]/div[2]/div/div[1]/div/div/span"));
                        String serviceTimeText = serviceTime.getText();
                        int counts2 = 0;
                        for (WebElement input : labelList) {
                            String value = input.getText();
                            arr02[counts2] = value;
                            counts2++;
                        }
                        /*** 工单数据和服务情况数据一起添加 * workOrderMap是工单 * SituationMap是服务情况 */
                        //遍历最终数据存到对象中
                        int workOrderInt = 0;
                        for (String s : arr02) {
                             if (workOrderInt == 1) {
                                 if (s!=null&&!s.isEmpty()){
                                     workOrderMap.put("clientName", s);
                                     SituationMap.put("clientName", s);
                                 }else{
                                     workOrderMap.put("clientName", null);
                                     SituationMap.put("clientName", null);
                                 }
                            }//护理员姓名
                            if (workOrderInt == 13) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("caregiverName", s);
                                    SituationMap.put("caregiverName", s);
                                }else{
                                    workOrderMap.put("caregiverName", null);
                                    SituationMap.put("caregiverName", null);
                                }
                            }//老人姓名
                            if (workOrderInt == 3) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("identityCard", s);
                                }else{
                                    workOrderMap.put("identityCard", null);
                                }
                            }//老人身份证
                            if (workOrderInt == 2) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("sreet", s);
                                }else{
                                    workOrderMap.put("sreet", null);
                                }
                            }//街道
                            if (workOrderInt == 9) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("position", s);
                                }else{
                                    workOrderMap.put("position", null);
                                }
                            }//职位
                            if (workOrderInt == 6) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("AddressDetall", s);
                                }else{
                                    workOrderMap.put("AddressDetall", null);
                                }
                            }//详细地址
                            if (workOrderInt == 5) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("ApplicationNumber", s);
                                }else{
                                    workOrderMap.put("ApplicationNumber", null);
                                }
                            }//申请号
                            if (workOrderInt == 8) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("workOrderNumber", s);
                                    SituationMap.put("workOrderNumber", s);
                                }else{
                                    workOrderMap.put("workOrderNumber", null);
                                    SituationMap.put("workOrderNumber", null);
                                }
                            }//工单号
                            if (workOrderInt == 4) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("EvaluationLervl", extractChineseNumber(s));
                                    SituationMap.put("EvaluationLervl", extractChineseNumber(s));
                                }else{
                                    workOrderMap.put("EvaluationLervl", null);
                                    SituationMap.put("EvaluationLervl", null);
                                }
                            }//评估等级
                            if (workOrderInt == 10) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("actualBeginTime", s.substring(11));
                                    SituationMap.put("beginTime", s.substring(11));
                                }else{
                                    workOrderMap.put("actualBeginTime", null);
                                    SituationMap.put("beginTime", null);
                                }
                            }//实际开始时间
                            if (workOrderInt == 12) {
                                if (statu3.equals("服务中")) {
                                    workOrderMap.put("actualEndtime", null);
                                    SituationMap.put("endtime", null);
                                }
                                if (statu3.equals("服务完成")) {
                                    workOrderMap.put("actualEndtime", s.substring(11));
                                    SituationMap.put("endtime", s.substring(11));
                                }
                            }//实际结束时间
                            if (workOrderInt == 14) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("checkGeographicalLocationLongitude", s);
                                    SituationMap.put("checkGeographicalLocationLongitude", s);
                                }else{
                                    workOrderMap.put("checkGeographicalLocationLongitude", null);
                                    SituationMap.put("checkGeographicalLocationLongitude", null);
                                }
                            }//签到经纬度
                            if (workOrderInt == 15) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("checkGeographicalLocationLatitude", s);
                                    SituationMap.put("checkGeographicalLocationLatitude", s);
                                }else{
                                    workOrderMap.put("checkGeographicalLocationLatitude", null);
                                    SituationMap.put("checkGeographicalLocationLatitude", null);
                                }
                            }//签到经纬度
                            if (workOrderInt == 17) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("serviceDuration", s);
                                    SituationMap.put("serviceDuration", s);
                                }else{
                                    workOrderMap.put("serviceDuration", null);
                                    SituationMap.put("serviceDuration", null);
                                }
                            }//服务时长
                            if (workOrderInt == 18) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("serviceContentId", serviceContentId(s));
                                    SituationMap.put("serviceContentId", serviceContentId(s));
                                }else{
                                    workOrderMap.put("serviceContentId", null);
                                    SituationMap.put("serviceContentId", null);
                                }
                            }//服务内容
                            //工单
                            if (statu3!=null&&!statu3.isEmpty()){
                                workOrderMap.put("status", statu3);//状态
                            }else{
                                workOrderMap.put("status", null);
                            }
                            if (serviceTimeText!=null&&!serviceTimeText.isEmpty()){
                                workOrderMap.put("date", serviceTimeText.substring(0, 10).replace("/", "-"));//日期
                                workOrderMap.put("beginTime", serviceTimeText.substring(11));//开始时间
                                LocalTime time = LocalTime.parse(serviceTimeText.substring(11));
                                String addedTime = String.valueOf(time.plusHours(1));
                                workOrderMap.put("endTime", addedTime + ":00");//结束时间
                                SituationMap.put("date", serviceTimeText.substring(0, 10).replace("/", "-"));//日期
                            }else{
                                workOrderMap.put("date", null);//日期
                                workOrderMap.put("beginTime", null);//开始时间
                                workOrderMap.put("endTime", null);//结束时间
                                SituationMap.put("date", null);//结束时间
                            }
                            //服务情况
                            if (statu3.equals("服务完成")) {
                                SituationMap.put("punchInSituation", "正常");//打卡情况
                                SituationMap.put("status", "已匹配");//状态
                            }
                            if (statu3.equals("服务中")) {
                                SituationMap.put("punchInSituation", "打卡中");//打卡情况
                                SituationMap.put("status", "未打卡");//状态
                            }
//                            SituationMap.put("status", statu3);//状态
                            //将数据添加工单列表里面
                            workOrderInt++;
                        }
                        //添加到工单数据
                        workOrder.add(workOrderMap);
                        //添加到服务情况数据
                        Situation.add(SituationMap);
                        logger.info((String) workOrderMap.get("caregiverName")+"-"+(String) workOrderMap.get("clientName")+"-"+statu3+"-"+serviceTimeText);
                    } else {
                        Thread.sleep(2000);
                        //最终详情中的数据
                        String[] arr02 = new String[35];
                        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div/div[2]/div/form")));
                        WebElement form = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div/div[2]/div/form"));
                        List<WebElement> labelList = form.findElements(By.xpath(".//span"));
                        //单独获取计划服务时间
                        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div/div[2]/div/form/div[3]/div[2]/div/div[1]/div/div/span")));
                        WebElement serviceTime = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/div/section/div/div/div[2]/div/form/div[3]/div[2]/div/div[1]/div/div/span"));
                        String serviceTimeText = serviceTime.getText();
                        int counts2 = 0;
                        for (WebElement input : labelList) {
                            String value = input.getText();
                            arr02[counts2] = value;
                            counts2++;
                        }
                        /*** 工单数据和服务情况数据一起添加 * workOrderMap是工单 * SituationMap是服务情况 */
                        //遍历最终数据存到对象中
                        int workOrderInt = 0;
                        for (String s : arr02) {
                            if (workOrderInt == 1) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("clientName", s);
                                    SituationMap.put("clientName", s);
                                }else{
                                    workOrderMap.put("clientName", null);
                                    SituationMap.put("clientName", null);
                                }
                            }//护理员姓名
                            if (workOrderInt == 13) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("caregiverName", s);
                                    SituationMap.put("caregiverName", s);
                                }else{
                                    workOrderMap.put("caregiverName", null);
                                    SituationMap.put("caregiverName", null);
                                }
                            }//老人姓名
                            if (workOrderInt == 3) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("identityCard", s);
                                }else{
                                    workOrderMap.put("identityCard", null);
                                }
                            }//老人身份证
                            if (workOrderInt == 2) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("sreet", s);
                                }else{
                                    workOrderMap.put("sreet", null);
                                }
                            }//街道
                            if (workOrderInt == 9) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("position", s);
                                }else{
                                    workOrderMap.put("position", null);
                                }
                            }//职位
                            if (workOrderInt == 6) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("AddressDetall", s);
                                }else{
                                    workOrderMap.put("AddressDetall", null);
                                }
                            }//详细地址
                            if (workOrderInt == 5) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("ApplicationNumber", s);
                                }else{
                                    workOrderMap.put("ApplicationNumber", null);
                                }
                            }//申请号
                            if (workOrderInt == 8) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("workOrderNumber", s);
                                    SituationMap.put("workOrderNumber", s);
                                }else{
                                    workOrderMap.put("workOrderNumber", null);
                                    SituationMap.put("workOrderNumber", null);
                                }
                            }//工单号
                            if (workOrderInt == 4) {
                                if (s!=null&&!s.isEmpty()){
                                    workOrderMap.put("EvaluationLervl", extractChineseNumber(s));
                                    SituationMap.put("EvaluationLervl", extractChineseNumber(s));
                                }else{
                                    workOrderMap.put("EvaluationLervl", null);
                                    SituationMap.put("EvaluationLervl", null);
                                }
                            }//评估等级
                            //工单
                            workOrderMap.put("actualBeginTime", null);//实际开始时间
                            workOrderMap.put("actualEndtime", null);//实际结束时间
                            workOrderMap.put("serviceDuration", null);//服务时长
                            workOrderMap.put("serviceContentId", null);//服务内容
                            workOrderMap.put("checkGeographicalLocationLongitude", null);//签到经纬度
                            workOrderMap.put("checkGeographicalLocationLatitude", null);//签退经纬度
                            if (serviceTimeText!=null&&!serviceTimeText.isEmpty()){
                                workOrderMap.put("date", serviceTimeText.substring(0, 10).replace("/", "-"));//日期
                                workOrderMap.put("beginTime", serviceTimeText.substring(11));//开始时间
                                LocalTime time = LocalTime.parse(serviceTimeText.substring(11));
                                String addedTime = String.valueOf(time.plusHours(1));
                                workOrderMap.put("endTime", addedTime + ":00");//结束时间
                                SituationMap.put("date", serviceTimeText.substring(0, 10).replace("/", "-"));//日期
                            }else{
                                workOrderMap.put("date", null);
                                workOrderMap.put("beginTime", null);
                                workOrderMap.put("endTime", null);
                                SituationMap.put("date", null);
                            }
                            //服务情况
                            SituationMap.put("serviceDuration", null);//服务时长
                            SituationMap.put("serviceContentId", null);//服务内容
                            SituationMap.put("checkGeographicalLocationLongitude", null);//签到经纬度
                            SituationMap.put("checkGeographicalLocationLatitude", null);//签退经纬度
                            SituationMap.put("punchInSituation", null);//打卡情况
                            if (statu3.equals("待服务")) {
                                SituationMap.put("status", "待激活");//状态
                                workOrderMap.put("status", "待服务");//状态
                            } else {
                                SituationMap.put("status", "已删除");//状态
                                workOrderMap.put("status", "已删除");//状态
                            }
                            //将数据添加工单列表里面
                            workOrderInt++;
                        }
                        //添加到工单数据
                        workOrder.add(workOrderMap);
                        //添加到服务情况数据
                        Situation.add(SituationMap);
                        logger.info((String) workOrderMap.get("caregiverName")+"-"+(String) workOrderMap.get("clientName")+"-"+statu3+"-"+serviceTimeText);
                    }
                    /**
                     *   这里数据已经拿到了下面去访问api
                     */
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    //最后工单数据
                    Calendar calendarWorkOrder = Calendar.getInstance();
                    workOrderInformation.put("time", dateFormat.format(calendarWorkOrder.getTime()));
                    workOrderInformation.put("workOrder", workOrder);
                    //最后服务情况数据
                    Calendar calendarSituation = Calendar.getInstance();
                    serviceSituation.put("time", dateFormat.format(calendarSituation.getTime()));
                    serviceSituation.put("workOrder", Situation);

//                    // 下面   测试数据  工单
//                    String pretty = JSON.toJSONString(workOrderInformation, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
//                            SerializerFeature.WriteDateUseDateFormat);
//                    String path = "C:\\Users\\邓昕劼\\Desktop";
//                    //判断文件是否存在
//                    File file = new File(path + "/工单.txt");
//                    if (file.exists()) {
//                    } else {
//                        try {
//                            file.createNewFile();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                    try {
//                        FileOutputStream fileOutputStream = new FileOutputStream(file);
//                        fileOutputStream.write(pretty.getBytes());
//                        fileOutputStream.close();
//                        System.out.println("工单json数据保存到成功！！！");
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    // 上面  测试数据所加
//
//                    // 下面   测试数据  服务情况
//                    String pretty1 = JSON.toJSONString(serviceSituation, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
//                            SerializerFeature.WriteDateUseDateFormat);
//                    //判断文件是否存在
//                    File file2 = new File(path + "/服务情况.txt");
//                    if (file2.exists()) {
//                    } else {
//                        try {
//                            file2.createNewFile();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                    try {
//                        FileOutputStream fileOutputStream = new FileOutputStream(file2);
//                        fileOutputStream.write(pretty1.getBytes());
//                        fileOutputStream.close();
//                        System.out.println("服务情况json数据保存到成功！！！");
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
                    // 上面  测试数据所加
//                    System.out.println("workOrderInformation = " + workOrderInformation);
//                    System.out.println("serviceSituation = " + serviceSituation);
                    //返回工单列表
                    //点击工单列表
                    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div/div[1]/div[1]/div/ul/div[2]/div[5]/li/ul/div[1]/a")));
                    WebElement wordInput2 = driver.findElement(By.xpath("//a/li/span[text()='工单列表']"));
                    ((JavascriptExecutor) driver).executeScript("arguments[0].click();", wordInput2);
                }
                WorkOrderSumIntCount++;
                logger.info("工单页数："+WorkOrderSumIntCount);
            }
            /**
             * 访问长护宝 老人导入接口  最后
             */
            logger.info(" 工单服务情况Api 登录长护宝获取token！");
            String[] workServiceStrList = token();
            token = workServiceStrList[0];
            sessionId = workServiceStrList[1];
            logger.info("token = " + token);
            logger.info("sessionId = " + sessionId);

            logger.info("开始访问长护宝 工单导入API");
            String  workOrderImport = test + "/api/wandaImport/workOrderImport";
            Map<String, String> workOrderHeaMap = new HashMap<>();
            workOrderHeaMap.put("Content-Type","application/json");
            workOrderHeaMap.put("token",token);
            workOrderHeaMap.put("Cookie","JSESSIONID="+sessionId);
            String workOrderResult = CloseableHttpClientUtil.doPostRaw(workOrderImport, workOrderInformation.toString(), workOrderHeaMap);
            logger.info("访问长护宝  工单导入API结果："+workOrderResult);
//            Thread.sleep(30000);
//            logger.info("开始访问长护宝 服务情况导入API");
//            String  serviceImport = test + "/api/wandaImport/serviceImport";
//            Map<String, String> serviceHeaMap = new HashMap<>();
//            serviceHeaMap.put("Content-Type","application/json");
//            serviceHeaMap.put("token",token);
//            serviceHeaMap.put("Cookie","JSESSIONID="+sessionId);
//            String serviceResult = CloseableHttpClientUtil.doPostRaw(serviceImport, serviceSituation.toString(), serviceHeaMap);
//            logger.info("访问长护宝  服务情况API结果："+serviceResult);



            Thread.sleep(3000);
            //退出浏览器
            driver.quit();
        } catch (Exception e) {
            e.printStackTrace();
            if (driver != null) {
                driver.quit();
                driver = null; // 可以将driver变量设置为null，以便在重新运行时重新创建它
            }
            Selenium(); // 发生异常重新调用方法
        }
    }


    /**
     * 服务内容
     */
    public String serviceContentId(String serviceContentId){
        String[] tasks = serviceContentId.split("\n");

        StringBuilder result = new StringBuilder();
        for (String task : tasks) {
            String name = task.replaceAll(" \\(.*\\)", ""); // 移除括号和里面的内容
            result.append(name).append(",");
        }
        String finalResult = result.toString();
        finalResult = finalResult.length() > 0 ? finalResult.substring(0, finalResult.length() - 1) : finalResult; // 移除最后一个逗号
        return finalResult;
    }

    /**
     * 获取长护宝得token、
     */
    public String[] token(){
        try {
            //json数据
            Map<String, String> data = new HashMap<>();
            data.put("password", "dxj123");
            data.put("phoneNumber", "17821950725");
            data.put("openid", "or30z5P3HMAbYR23HYAjgsclVw3E");
            data.put("name", "dxj");
            //登录长护宝后端系统拿到Token
            String Token_data = HttpClientExample.post(LoginUrl, data, "POST");
            // 使用 Jackson ObjectMapper 解析 JSON
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(Token_data);
            // 提取 token
            String token = jsonNode.path("data").path("token").asText();
            // 提取 sessionId
            String sessionId = jsonNode.path("data").path("sessionId").asText();
            String[] strArray = new String[2];
            // 存储数据
            strArray[0] = token;
            strArray[1] = sessionId;
            return strArray;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    //********************** 等待元素可见的方法 *********************************
    private static void waitPageLoadComplete(WebDriver driver, int timeoutInSeconds) {
        WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);

        wait.until(webDriver ->
                ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));

        // 等待一些其他可能的条件，例如页面上的某个元素可见等
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div/div/div[2]/div/section/div/div[2]/div[1]/div[3]/div[1]/div[2]/div[1]/div[3]/table/tbody")));
    }


    // 等待元素可见的方法
    public WebElement waitForElementVisible(WebDriver driver, By locator) {
        WebDriverWait wait = new WebDriverWait(driver, 40); // 最多等待10秒
        return wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
    }

    private static int extractChineseNumber(String input) {
        // 获取字符串的第一个字符
        if (input!=null&& !input.isEmpty()) {
            String firstChar = String.valueOf(input.charAt(0));
            if (firstChar.equals("一")) {
                return 1;
            }
            if (firstChar.equals("二")) {
                return 2;
            }
            if (firstChar.equals("三")) {
                return 3;
            }
            if (firstChar.equals("四")) {
                return 4;
            }
            if (firstChar.equals("五")) {
                return 5;
            }
            if (firstChar.equals("六")) {
                return 6;
            }
            if (firstChar.equals("七")) {
                return 7;
            }
            if (firstChar.equals("八")) {
                return 8;
            }
            if (firstChar.equals("九")) {
                return 9;
            }
        }
        return 0;

    }


}
